import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Input, Card, List, Tag, Space, Typography, Empty, Spin, Divider, Button } from 'antd';
import { SearchOutlined, FileOutlined, FileTextOutlined, FilePdfOutlined, FileImageOutlined, FileUnknownOutlined } from '@ant-design/icons';
import { search, getSearchSuggestions, SearchParams } from '../../api/search';

const { Title, Paragraph, Text } = Typography;
const { Search } = Input;

const SearchPage: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const queryParams = new URLSearchParams(location.search);
  const keywordFromUrl = queryParams.get('keyword') || '';

  const [keyword, setKeyword] = useState(keywordFromUrl);
  const [loading, setLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<any>({ items: [], total: 0 });
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 搜索参数
  const [searchParams, setSearchParams] = useState<SearchParams>({
    keyword: keywordFromUrl,
    page: 1,
    size: 10,
    sortBy: 'relevance',
    sortOrder: 'desc',
  });

  // 执行搜索
  const performSearch = async () => {
    if (!searchParams.keyword) return;

    try {
      setLoading(true);
      const results = await search(searchParams);
      setSearchResults(results);
    } catch (error) {
      console.error('搜索失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取搜索建议
  const fetchSuggestions = async (value: string) => {
    if (!value) {
      setSuggestions([]);
      return;
    }

    try {
      const res = await getSearchSuggestions(value);
      setSuggestions(res.map(item => item.text));
    } catch (error) {
      console.error('获取搜索建议失败:', error);
    }
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setKeyword(value);
    setSearchParams({
      ...searchParams,
      keyword: value,
      page: 1,
    });
    navigate(`/search?keyword=${encodeURIComponent(value)}`);
  };

  // 处理分页变化
  const handlePageChange = (newPage: number, newPageSize?: number) => {
    setPage(newPage);
    if (newPageSize) setPageSize(newPageSize);
    setSearchParams({
      ...searchParams,
      page: newPage,
      size: newPageSize || pageSize,
    });
  };

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    if (!fileType) return <FileOutlined />;
    
    switch (fileType.toLowerCase()) {
      case 'pdf':
        return <FilePdfOutlined />;
      case 'doc':
      case 'docx':
      case 'txt':
        return <FileTextOutlined />;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return <FileImageOutlined />;
      default:
        return <FileUnknownOutlined />;
    }
  };

  // URL参数变化时执行搜索
  useEffect(() => {
    if (keywordFromUrl) {
      setKeyword(keywordFromUrl);
      setSearchParams({
        ...searchParams,
        keyword: keywordFromUrl,
        page: 1,
      });
    }
  }, [location.search]);

  // 搜索参数变化时执行搜索
  useEffect(() => {
    if (searchParams.keyword) {
      performSearch();
    }
  }, [searchParams]);

  return (
    <div>
      <Card>
        <Title level={2}>知识搜索</Title>
        <Search
          placeholder="输入关键词搜索知识..."
          enterButton={<Button type="primary" icon={<SearchOutlined />}>搜索</Button>}
          size="large"
          value={keyword}
          onChange={(e) => {
            setKeyword(e.target.value);
            fetchSuggestions(e.target.value);
          }}
          onSearch={handleSearch}
          style={{ marginBottom: 24 }}
        />

        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : searchResults.items.length > 0 ? (
          <>
            <div style={{ marginBottom: 16 }}>
              <Text>找到 {searchResults.total} 条结果 (搜索耗时: {searchResults.took || 0}ms)</Text>
            </div>

            <List
              itemLayout="vertical"
              size="large"
              pagination={{
                current: page,
                pageSize: pageSize,
                total: searchResults.total,
                onChange: handlePageChange,
                showSizeChanger: true,
                showQuickJumper: true,
              }}
              dataSource={searchResults.items}
              renderItem={(item: any) => (
                <List.Item
                  key={item.id}
                  actions={[
                    <Space key="tags">
                      {item.tags && item.tags.map((tag: string) => (
                        <Tag key={tag} color="blue">{tag}</Tag>
                      ))}
                    </Space>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={getFileIcon(item.fileType)}
                    title={<a href={`/knowledge/${item.id}`}>{item.title}</a>}
                    description={
                      <Space>
                        <Text type="secondary">更新于: {new Date(item.updatedAt).toLocaleString()}</Text>
                        {item.categoryName && <Text type="secondary">分类: {item.categoryName}</Text>}
                      </Space>
                    }
                  />
                  {item.highlight ? (
                    <div dangerouslySetInnerHTML={{ __html: `...${item.highlight}...` }} />
                  ) : (
                    <Paragraph ellipsis={{ rows: 2 }}>{item.description || '无描述'}</Paragraph>
                  )}
                </List.Item>
              )}
            />
          </>
        ) : searchParams.keyword ? (
          <Empty description="未找到匹配的知识内容" />
        ) : null}
      </Card>
    </div>
  );
};

export default SearchPage;